import { useTitle } from 'ahooks'
import style from './style.less'
import { useSearchParams, history } from 'umi';
import React, { useEffect, useState } from 'react'
import { Modal, Button, Form, Popup, Input, Stepper, Toast } from 'antd-mobile';
import { PhoneFill } from 'antd-mobile-icons'
import SRC from '@/images/supply/invoice.png'
import Shop from '@/images/supply/shop.png'
import moment from 'moment';
import { getInformationById, getUserPhone } from '@/services/Publish';
import { temGoodsDto } from '../hall/.info/.item';
import { userContactInfo } from '../order/list/confirm/.item';

export default () => {
    useTitle('供应详情')
    const [data, setData] = useState<temGoodsDto>({} as temGoodsDto)
    const [userInfo,setUserInfo] = useState<userContactInfo>({} as userContactInfo)
    const [visible, setVisible] = React.useState<boolean>(false);
    const [visible2, setVisible2] = React.useState<boolean>(false);
    const [searchParams] = useSearchParams();
    const [quantity, setQuantity] = useState(1);
    const [price, setPrice] = useState('');
    const [total, setTotal] = useState(0);
    const [form] = Form.useForm();

    const query = {
        id: String(searchParams.get('id'))
    }

    const getData = async () => {
        const res = await getInformationById(query.id)
        const userInfo = await getUserPhone(res.userId)
        setUserInfo(userInfo)
        console.log(res);
        setData(res)
    }

    useEffect(() => {
        getData()
    }, [])

    const onOk = () => {
        form.validateFields().then(values => {
            const { expectedPrice, expectedAmount } = values;
            console.log(values);

            if (expectedPrice <= 0 || expectedAmount <= 0) {
                Toast.show('数量和金额必须大于0');
                return;
            }
            else if (expectedPrice > 99999.99 || expectedAmount > 99999.99) {
                Toast.show('数量和金额最大值为99999.99');
                return;
            }
            else if (expectedAmount > data.quantity) {
                Toast.show('采购数量不能大于商品数量');
                return;
            }
            // 校验通过，可以提交表单了
            setVisible(false);
            const field1 = values.expectedAmount
            const field2 = values.expectedPrice
            const queryString = `?expectedAmount=${field1}&expectedPrice=${field2}&id=${query.id}`;
            history.push(`/supply/detail/confirm${queryString}`)
        }).catch(error => {
            console.log('校验失败', error);
        });

    }
    const handleQuantityChange = (value: any) => {
        setQuantity(value);
        calculateTotal(value, price);
    };

    const handlePriceChange = (event: any) => {
        const value = event;
        setPrice(value);
        calculateTotal(quantity, event);
    };

    const calculateTotal = (quantity: number, price: string) => {
        const result = quantity * Number(price);
        setTotal(result);
    };

    return (
        <div className={style.page}>
            <div className={style.content}>
                <div
                    className={style.img}
                    style={{ backgroundImage: `url(${data?.picture || ''})` }}
                />
                <div className={style.info}>
                    <div className={style.tip}>
                        <div className={style.red}>
                            ¥{data.minPrice}-{data.maxPrice}
                        </div>
                        <div>{moment(data?.updateTime).format('YYYY-MM-DD')}更新</div>
                    </div>
                    <div className={style.title}>{data.commodityName}</div>
                    {data.supportBilling ? null :
                        <div className={style.red}>
                            <img src={SRC} alt='src' className={style.src} />
                            不支持在线开票
                        </div>
                    }
                    <div className={style.center}>
                        <div className={style.item}>
                            <div className={style.note}>商品数量</div>
                            <div>
                                {data.quantity}/斤
                            </div>
                        </div>
                        <div className={style.item}>
                            <div className={style.note}>发货地</div>
                            <div>
                                {data.shipmentPlace}
                            </div>
                        </div>
                        <div className={style.item}>
                            <div className={style.note}>产地</div>
                            <div>
                                {data.originPlace}
                            </div>
                        </div>
                    </div>
                    <div className={style['seller-info']}>
                        <div className={style['seller-tow']}>
                            <img src={Shop} alt='shop' className={style['left-icon']} />
                            <div>
                                <div className={style.shopping}>四季化肥批发</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className={style.remark}>{data.description}</div>
                {data.qualification?.map((i,index) => (
                    <div key={index} className={style['detail-img']}>
                        <img src={i} alt="" />
                    </div>
                ))}
            </div>
            <div className={style['btn-warp']}>
                <div
                    onClick={async () => {
                        setVisible(true);
                    }}
                >
                    生成采购订单
                </div>
                <div
                    className={style.green}
                    onClick={async () => {
                        setVisible2(true);
                    }}
                >
                    <PhoneFill style={{ marginRight: '5px' }} />
                    联系商家
                </div>
            </div>

            <Popup
                visible={visible}
                showCloseButton={true}
                onClose={() => {
                    setVisible(false);
                }}
            >
                <Form form={form} onFinish={onOk}>
                    <div className={style.modal}>
                        <div className={style.content}>
                            <div
                                className={style.img}
                                style={{ backgroundImage: `url(${data.picture})` }}
                            />
                            <div className={style.info}>
                                <div className={style.tip}>{data.commodityName}</div>
                                <div className={style.money}>
                                    ￥{data.minPrice}-{data.maxPrice}
                                </div>
                            </div>
                        </div>
                        <div className={style.line}>
                            <div className={style.label}>数量</div>
                            <div className={style.control}>
                                <Form.Item
                                    childElementPosition='right'
                                    name='expectedAmount'
                                    initialValue={1}
                                >
                                    <Stepper
                                        max={99999.99}
                                        min={1}
                                        value={quantity}
                                        className={style.stepper}
                                        onChange={handleQuantityChange}
                                    />
                                </Form.Item>
                            </div>
                        </div>
                        <div className={style.line}>
                            <div className={style.label}>采购单价</div>
                            <div className={style.control}>
                                <Form.Item
                                    name='expectedPrice'
                                    rules={[{ required: true, message: '金额不能为空' },
                                    ]}
                                >
                                    <Input
                                        type='number'
                                        value={price}
                                        placeholder='请输入金额'
                                        className={style.inputs}
                                        clearable
                                        onChange={handlePriceChange}
                                    />
                                </Form.Item>
                            </div>
                        </div>
                        <div className={style.line}>
                            <div className={style.label}>合计</div>
                            <div className={style.control}>
                                <span className={style.money}>￥{total.toFixed(2)}</span>
                            </div>
                        </div>
                        <Button color="primary" block
                            size='large' style={{ backgroundColor: '#21B47C' }}
                            onClick={() => { form.submit() }}
                        >
                            确定
                        </Button>
                    </div>
                </Form>
            </Popup>

            <Modal
                visible={visible2}
                onClose={() => {
                    setVisible2(false);
                }}
                title="联系方式"
                className={style.modal2}
                showCloseButton={true}
                content={(
                    <div className={style['info-warp']}>
                        <div className={style.line2}>
                            <div className={style.info}>
                                <div className={style.tip}>以下是商家的联系方式，请电话联系</div>
                                <div className={style.phone}>
                                    <span>
                                        {userInfo.contactName ? `${userInfo.contactName} ` : ''}
                                        {userInfo.contactPhone}
                                    </span>
                                </div>
                            </div>
                            <div
                                className={style.icon}
                                onClick={() => {
                                    // window.location.href = `tel:${detailData.contactMobile}`;
                                }}
                            >
                                <div>
                                    <PhoneFill style={{ marginLeft: '5px' }} />
                                </div>
                                呼叫
                            </div>
                        </div>
                    </div>)}
            />

        </div>
    )
}
